package com.yanqu.road.server.gameplayer.module.task;

import com.yanqu.road.dao.impl.player.UserCommonActivityDataDaoImpl;
import com.yanqu.road.entity.autodata.task.OldTaskChangeConfigData;
import com.yanqu.road.entity.autodata.task.UserObjectTaskData;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.event.GameEvent;
import com.yanqu.road.entity.event.GameObjectEvent;
import com.yanqu.road.entity.event.IEvent;
import com.yanqu.road.entity.event.IObjectEvent;
import com.yanqu.road.entity.task.TaskConditionInfo;
import com.yanqu.road.entity.task.TaskInfo;
import com.yanqu.road.entity.task.UserTaskActive;
import com.yanqu.road.entity.task.UserTaskData;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.logic.bussiness.player.UserTaskBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.TaskPb;
import com.yanqu.road.pb.task.ObjectTaskProto;
import com.yanqu.road.pb.task.TaskProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.businessdepart.BusinessDepartModule;
import com.yanqu.road.server.gameplayer.module.activity.recallplayer.RecallPlayerModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.*;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.gameplayer.module.specialcookboy.SpecialCookBoyModule;
import com.yanqu.road.server.logic.task.BaseCondition;
import com.yanqu.road.server.logic.task.BaseObjectCondition;
import com.yanqu.road.server.logic.task.BaseTaskData;
import com.yanqu.road.server.logic.task.TaskConditionMail;
import com.yanqu.road.server.manger.ConfigMgr;
import com.yanqu.road.server.manger.DataAnalyticsMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.config.OldTaskChangeMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.config.TaskMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.relatives.RelativesMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 任务模块
 */
public class TaskModule extends GeneralModule {

    private Map<Integer, UserTaskData> userTaskDataMap;

    private List<UserTaskData> fixStateTaskList = new ArrayList<>();
    /**
     * 当前正在执行的主线任务id
     */
    private int curMainTaskId = Integer.MAX_VALUE;
    /**
     * 主线任务id
     */
    private int realMainTaskId;
    /**
     * 玩家的当天积分
     */
    private UserTaskActive userTaskActive;

    private final IEvent gameEvent;

    private Map<Integer, BaseTaskData> baseTaskDataMap;

    private Map<Integer, BaseTaskData> showBaseTaskDataMap = new HashMap<>();
    /**
     * 临时改变的任务列表
     */
    private List<BaseTaskData> changedBaseTaskDataList = new ArrayList<>();

    private AtomicInteger changeCount = new AtomicInteger();


    private final IObjectEvent gameObjectEvent;
    /**
     * 指定对象的任务 key1 completeType key2 objectId
     */
    private Map<Integer, Map<Integer, UserObjectTaskData>> userObjectTaskDataMap = new HashMap<>();
    private Set<UserObjectTaskData> objectTaskChangeSet = new HashSet<>();
    private List<UserTaskData> waitSaveDataList = new ArrayList<>();

    public TaskModule(GamePlayer player) {
        super(player);
        this.gameEvent = new GameEvent();
        this.gameObjectEvent = new GameObjectEvent();
    }

    @Override
    public boolean loadData() {
        baseTaskDataMap = new ConcurrentHashMap<>();
        userTaskDataMap = UserTaskBussiness.getUserTaskDataMap(player.getUserId());
        userTaskActive = UserTaskBussiness.getUserTaskActive(player.getUserId());

        loadObjectTaskDb();
        transformOldTaskDataToObjectTask();
        loadObjectTaskCondition(this.userObjectTaskDataMap);

        initUserTaskActive();
        resetActive();

        // 默认拿主线任务的第一条   mgr的mainTaskList 第一个索引
        int maxIndex = 0;
        int curTaskId = 0;
        for (UserTaskData userTaskData : userTaskDataMap.values()) {
            if (userTaskData.getTaskType() == eTaskType.Main.getValue()) {
                int index = TaskMgr.getMainTaskIndex(userTaskData.getTaskId());
                if (index > maxIndex) {
                    maxIndex = index;
                    curTaskId = userTaskData.getTaskId();
                }
            }
        }
        // 临时修复, 如果当前的用户的任务数据都是已完成的，需要加载出下一条
        UserTaskData mainTaskInfo = getUserTaskData(curTaskId);
        maxIndex = getMaxIndex(maxIndex, mainTaskInfo);
        if (null != TaskMgr.getTaskMap()) {
            for (TaskInfo taskInfo : TaskMgr.getTaskMap().values()) {
                if (OldTaskChangeMgr.isNeedTransformTask(taskInfo.getType())) {//废弃的任务不要重复生成
                    continue;
                }
                if (TaskMgr.isObjectTask(taskInfo.getType())) {//指定对象任务这里不生成
                    continue;
                }
                //如果已存在任务则不重新生成 否则重新生成
                UserTaskData userTaskData = getUserTaskData(taskInfo.getTaskId());
                if(null != userTaskData) {
                    //财神密卷不用改状态，会轮回重置且一次性全部下发
                    if (userTaskDataMap.containsKey(taskInfo.getNextTaskId()) && userTaskData.getState() == 0 && !isSecretVolumeTask(taskInfo)) {
                        //藏宝也不重置
                        if(taskInfo.getType() != eTaskType.CurioScoreTask.getValue()) {
                            userTaskData.setState(1);
                            fixStateTaskList.add(userTaskData);
                        }
                    }
                    if (taskInfo.getType() == eTaskType.Main.getValue()) {
                        if(taskInfo.getTaskId() > realMainTaskId && realMainTaskId < curMainTaskId){
                            realMainTaskId = taskInfo.getTaskId();
                        }
                        if (taskInfo.getTaskId() < curMainTaskId && userTaskData.getState() == 0) {
                            curMainTaskId = taskInfo.getTaskId();
                            realMainTaskId = curMainTaskId;
                        }
                    }
                }else {
                    // 主线任务只加载当前这一条
                    if (taskInfo.getType() == eTaskType.Main.getValue()) {
                        if (TaskMgr.getMainTaskIndex(taskInfo.getTaskId()) != maxIndex) {
                            continue;
                        }
                    }
                    // 成就也只加载这一条，前置任务非0且上一条完成才加载
                    if (taskInfo.getType() == eTaskType.Achievement.getValue() ||
                            taskInfo.getType() == eTaskType.GrandChildExamTask.getValue() ||
                            taskInfo.getType() == eTaskType.DrugStoreChuFangLevel.getValue() ||
                            taskInfo.getType() == eTaskType.Kuang.getValue() ||
                            taskInfo.getType() == eTaskType.KowloonHero.getValue() ||
                            taskInfo.getType() == eTaskType.SpecialCookBoyPassLevelNum.getValue() ||
                            taskInfo.getType() == eTaskType.MusicRoom.getValue() ||
                            taskInfo.getType() == eTaskType.IceServerMainTask.getValue() ||
                            taskInfo.getType() == eTaskType.IceServerSubTask.getValue()
                    ) {
                        if (taskInfo.getPreTaskId() != 0 && (getUserTaskData(taskInfo.getPreTaskId()) == null || getUserTaskData(taskInfo.getPreTaskId()).getState() != 1)) {
                            continue;
                        }
                    }
                    //家具目标开启条件不满足时不开启任务
                    if (taskInfo.getType() == eTaskType.WingRoomUnLock.getValue()) {
                        if (!SystemOpenMgr.systemOpen(player, eSystemId.WingRoomUnlockTask.getValue())) {
                            continue;
                        }
                    }

                    if (taskInfo.getType() == eTaskType.MusicRoom.getValue()){
                        if (!SystemOpenMgr.systemOpen(player, eSystemId.MusicRoom.getValue())){
                            continue;
                        }
                    }
                    if (taskInfo.getType() == eTaskType.MammonDecorationCount.getValue()) {
                        if (!SystemOpenMgr.systemOpen(player, eSystemId.Mammon.getValue())){
                            continue;
                        }
                    }
                    if (taskInfo.getType() == eTaskType.CurioScoreTask.getValue()){
                        if (!SystemOpenMgr.systemOpen(player, eSystemId.Curio.getValue())){
                            continue;
                        }
                    }
                    TaskConditionInfo taskConditionInfo = TaskMgr.getTaskConditionById(taskInfo.getTaskId());
                    if(null != taskConditionInfo){
                        if (taskConditionInfo.getType() == eGamePlayerEventType.CricketUpTitle.getValue()) {
                            // 获取开服天数
                            int serverOpenDay = ServerListMgr.getServerOpenDay(GameServer.getInstance().getServerId());
                            if (player.getTitleId() > 5 && serverOpenDay >= GameConfig.CRICKET_OPEN_DAY) {
                                addTask(taskInfo);
                            }
                        } else {
                            addTask(taskInfo);
                        }
                    }
                }
            }
        }

        // 加载已有的任务
        for (Map.Entry<Integer, UserTaskData> entry : userTaskDataMap.entrySet()) {
            addTaskFromUserTaskData(entry.getValue());
        }

        // 如果是日常任务的话 把过时的日期设置为当天 并初始化任务状态
        resetOneDay();
        resetSecretVolumeSevenDay(false);
        return true;
    }

    private int getMaxIndex(int maxIndex, UserTaskData mainTaskInfo) {
        if (mainTaskInfo != null && mainTaskInfo.getState() == 1) {
            maxIndex = maxIndex + 1;
        }
        return maxIndex;
    }

    @Override
    public boolean afterLoadData() {
        AttributeModule attributeModule = player.getModule(AttributeModule.class);
        player.notifyListener(eGamePlayerEventType.JoinUnion.getValue(), player.getUserInfo());  //离线时候被踢，登录时候检测
        player.notifyListener(eGamePlayerEventType.JoinUnionActivityCondition.getValue(), player.getUserInfo());
        player.notifyListener(eGamePlayerEventType.MoveEstateBuilding.getValue(), player.getModule(EstateWarModule.class).getUserEstateWarData());      //离线时被打掉
        player.notifyListener(eGamePlayerEventType.MoveEstateBuildingFloor.getValue(), player.getModule(EstateWarModule.class).getUserEstateWarData()); //离线时被打掉
        player.notifyListener(eGamePlayerEventType.EstateWarTotalBeRobTimes.getValue(), player.getModule(EstateWarModule.class).getUserEstateWarData());//离线时被揍
        player.notifyListener(eGamePlayerEventType.MarriageTotalTimes.getValue(), player.getModule(MarriageModule.class).getUserMarriageData());          //离线时联姻成功
        player.notifyListener(eGamePlayerEventType.BeWantedTotalTimes.getValue(), player.getModule(TradeWarModule.class).getUserTradeWarInfo());          //离线时被通缉
        player.notifyListener(eGamePlayerEventType.TradeWarTotalBeKillPatronsCount.getValue(), player.getModule(TradeWarModule.class).getUserTradeWarInfo());  //离线时候被揍
        player.notifyListener(eGamePlayerEventType.MineWarMaxTeamReward.getValue(), player.getModule(MineWarModule.class).getUserMineData());   //过期自动撤回
        player.notifyListener(eGamePlayerEventType.RankActivityTopThreeTotalTimes.getValue(), player.getModule(PlayerModule.class).getUserHistoryAttribute()); //离线自动发奖励
        player.notifyListener(eGamePlayerEventType.TotalBeGiveLikeTimes.getValue(), attributeModule.getAttribute(ePlayerAttrType.TotalBeGiveLikeTimes));  //离线被点赞
        player.notifyListener(eGamePlayerEventType.TotalBeHateTimes.getValue(), attributeModule.getAttribute(ePlayerAttrType.TotalBeHateTimes));   //离线时被蛊惑
        player.notifyListener(eGamePlayerEventType.RelativesCount.getValue(), RelativesMgr.getRelativesNum(player.getUserId()));    //离线时亲家数量变化
        int memberCount = 0;
        String unionUid = player.getUserInfo().getUnionUid();
        if(!StringUtils.isNullOrEmpty(unionUid)){
            UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
            if(null != unionInfo){
                memberCount = unionInfo.getMemberCount();
            }
        }
        player.notifyListener(eGamePlayerEventType.UnionMemberCount.getValue(), memberCount);         //商会成员
        return true;
    }

    @Override
    public boolean saveData() {
        List<BaseTaskData> tempQuestList = new ArrayList<>(baseTaskDataMap.values());
        for (BaseTaskData quest : tempQuestList) {
            UserTaskData userTaskData = quest.getUserTaskData();
            if (userTaskData == null) {
                continue;
            }
            if (quest.getUserTaskData().isInsertOption()) {
//                if (userTaskData.getState() != 0 || !userTaskData.getValue().equals(BigInteger.ZERO) || titleId >=5 ) {
                    UserTaskBussiness.addUserTaskData(quest.getUserTaskData());
//                }
            } else if (quest.getUserTaskData().isUpdateOption()) {
                UserTaskBussiness.updateUserTaskData(quest.getUserTaskData());
            }
        }

        if (null != userTaskActive) {
            if (userTaskActive.isInsertOption()) {
                UserTaskBussiness.addUserTaskActive(userTaskActive);
            } else if (userTaskActive.isUpdateOption()) {
                UserTaskBussiness.updateUserTaskActive(userTaskActive);
            }
        }
        if (null != fixStateTaskList && fixStateTaskList.size() > 0) {
            List<UserTaskData> tempList = new ArrayList<>(fixStateTaskList);
            fixStateTaskList.clear();
            for (UserTaskData data : tempList) {
                UserTaskBussiness.updateUserTaskData(data);
            }
        }

        List<UserTaskData> tempSaveList = new ArrayList<>();
        synchronized (waitSaveDataList) {
            tempSaveList = new ArrayList<>(waitSaveDataList);
            waitSaveDataList.clear();
        }

        for (UserTaskData userTaskData : tempSaveList) {
            if (userTaskData.isInsertOption()) {
                UserTaskBussiness.addUserTaskData(userTaskData);
            } else if (userTaskData.isUpdateOption()) {
                UserTaskBussiness.updateUserTaskData(userTaskData);
            }
        }

        for (Map<Integer, UserObjectTaskData> dataMap : userObjectTaskDataMap.values()) {
            for (UserObjectTaskData userObjectTaskData : dataMap.values()) {
                UserCommonActivityDataDaoImpl.save(userObjectTaskData);
            }
        }
        return true;
    }

    @Override
    public void loginSendMsg() {
        syncTaskConfig();

        syncUserTaskData();
        syncTaskActive();
        syncSevenDayActive();

        syncUserObjectTaskData();
    }

    /**
     * 获取所有类型财神旧成就的最大值
     */
    public Map<Integer,Integer> getMaxConditionValue() {
        Map<Integer,Integer> mammonTaskMaxValueMap = new HashMap<>();
        for (UserTaskData userTaskData : userTaskDataMap.values()) {
            if (userTaskData.getTaskType() == eTaskType.MammonDecorationCount.getValue()){
                TaskConditionInfo taskConditionInfo = TaskMgr.getTaskConditionById(userTaskData.getTaskId());
                if (taskConditionInfo == null){
                    continue;
                }
                List<BigInteger> paramList = taskConditionInfo.getParamList();
                if (paramList == null || paramList.size() < 4){
                    continue;
                }
                int decorationType = paramList.get(1).intValue();
                if (!mammonTaskMaxValueMap.containsKey(decorationType)){
                    mammonTaskMaxValueMap.put(decorationType,0);
                }else {
                    int maxValue = mammonTaskMaxValueMap.get(decorationType);
                    if (maxValue < userTaskData.getValue().intValue()){
                        mammonTaskMaxValueMap.put(decorationType,userTaskData.getValue().intValue());
                    }
                }
            }
        }
        return mammonTaskMaxValueMap;

    }


    private void initUserTaskActive() {
        long nowTime = System.currentTimeMillis() / 1000;
        if (null == userTaskActive) {
            UserTaskActive taskActive = new UserTaskActive();
            taskActive.setUserId(player.getUserId());
            taskActive.setTaskActive(0);
            taskActive.setTaskGetRewardIndexList(new ArrayList<>());
            taskActive.setLastUpdateTime(nowTime);
            taskActive.setSevenDayStartTime(nowTime);
            taskActive.setSevenDayActive(0);
            taskActive.setSevenDayGetRewardIndexList(new ArrayList<>());
            taskActive.setInsertOption();
            userTaskActive = taskActive;
        }
        if(0 == userTaskActive.getSevenDayStartTime()){
            userTaskActive.setSevenDayStartTime(nowTime);
        }
    }

    /**
     * 同步全部任务
     */
    private void syncUserTaskData() {
        List<BaseTaskData> tempList = new ArrayList<>(getShowBaseTaskDataMap().values());

        TaskProto.TaskDataListMsg.Builder listMsg = TaskProto.TaskDataListMsg.newBuilder();
        for(BaseTaskData baseTaskData : tempList){
            TaskInfo taskInfo = TaskMgr.getTaskMap().get(baseTaskData.getTaskId());
            if(null == taskInfo){
                log.info("not task {}", baseTaskData.getTaskId());
                continue;
            }
            listMsg.addDataList(TaskPb.parseTaskDataTempMsg(baseTaskData.getTaskId(), baseTaskData.getUserTaskData()));
        }
        player.sendPacket(Protocol.U_TASK_DATA_SEND, listMsg);
    }

    /**
     * 同步任务活跃度
     */
    public void syncTaskActive() {
        TaskProto.TaskActiveMsg.Builder msg = TaskPb.parseTaskActiveMsg(userTaskActive);
        if(null != msg) {
            player.sendPacket(Protocol.U_TASK_ACTIVE_SYNC, msg);
        }
    }

    /**
     * 同步七日任务活跃度
     */
    private void syncSevenDayActive() {
        TaskProto.SevenDayActiveMsg.Builder msg = TaskPb.parseSevenDayActiveMsg(userTaskActive);
        if (null != msg) {
            player.sendPacket(Protocol.U_TASK_SEVEN_DAY_ACTIVE_SYNC, msg);
        }
    }

    /**
     * 同步商帮,矿山,榷场的任务配置
     */
    private void syncTaskConfig() {
        TaskProto.TaskConfigSyncMsg.Builder builder = TaskMgr.getTaskConfigSyncMsg();
        player.sendPacket(ClientProtocol.U_TASK_CONFIG_SEND, builder);
    }

    public void addTaskActive(int taskActive) {
        userTaskActive.setTaskActive(userTaskActive.getTaskActive() + taskActive);
        userTaskActive.setLastUpdateTime(System.currentTimeMillis() / 1000);
        player.getModule(RecallPlayerModule.class).updateTaskFromSystem(eRecallPlayerConditionTypeEnum.activeDuringBack, BigInteger.valueOf(userTaskActive.getTaskActive()));
        player.notifyListener(eGamePlayerEventType.ZfbActivityActive.getValue(), userTaskActive.getTaskActive());
        //商途启程
        player.getModule(BusinessDepartModule.class).updateDailyActive(userTaskActive.getTaskActive());
        syncTaskActive();// 同步修改后的积分
    }

    public void addSevenDayActive(int taskActive) {
        userTaskActive.setSevenDayActive(userTaskActive.getSevenDayActive() + taskActive);
        syncSevenDayActive();
    }

    public TaskProto.TaskGetRewardRespMsg.Builder getTaskReward(int taskId){
        TaskProto.TaskGetRewardRespMsg.Builder msg = TaskProto.TaskGetRewardRespMsg.newBuilder();
        // 判断该任务是否完成
        BaseTaskData baseTaskData = baseTaskDataMap.get(taskId);
        if(null == baseTaskData){
            msg.setRet(GameErrorCode.E_TASK_NO_FOUND);
            return msg;
        }
        TaskInfo taskInfo = TaskMgr.getTaskInfoById(taskId);
        if(null == taskInfo){
            msg.setRet(GameErrorCode.E_TASK_NO_FOUND);
            return msg;
        }
        if (baseTaskData.getUserTaskData() == null) {
            baseTaskData.initUserTaskData();
        }
        if (baseTaskData.getUserTaskData() == null) {
            msg.setRet(GameErrorCode.E_TASK_NO_FOUND);
            return msg;
        }
        if(baseTaskData.getUserTaskData().getState() == 1){
            msg.setRet(GameErrorCode.E_TASK_ALREADY_GET_REWARD);
            int nextTaskId = taskInfo.getNextTaskId();
            if (nextTaskId > 0) {
                BaseTaskData nextQuest = baseTaskDataMap.get(nextTaskId);
                if (null == nextQuest) {
                    // 初始化下一条
                    TaskInfo nextTaskInfo = TaskMgr.getTaskInfoById(nextTaskId);
                    if (nextTaskInfo != null) {
                        addTask(nextTaskInfo);
                    }
                }
                nextQuest = baseTaskDataMap.get(nextTaskId);
                if (null != nextQuest) {
                    msg.setNextTask(TaskPb.parseTaskDataTempMsg(nextQuest.getTaskId(), nextQuest.getUserTaskData()));
                }
            }
            return msg;
        }
        if(!baseTaskData.canCompleted()) {
            msg.setRet(GameErrorCode.E_TASK_NOT_COMPLETE);
            return msg;
        }
        if(taskInfo.getType() == eTaskType.SevenDay.getValue()){
            if(getSevenDayOffsetDays() > 8){
                msg.setRet(GameErrorCode.E_TASK_SEVEN_DAY_OVER_NO_REWARD);
                return msg;
            }
        }

        startChanges();
        // 设置任务已经完成
        baseTaskData.finish();
        if (taskInfo.getType() == eTaskType.Main.getValue()) {
            realMainTaskId = curMainTaskId;
            curMainTaskId = Integer.MAX_VALUE;
        }
        AttributeModule attributeModule = player.getModule(AttributeModule.class);
        if (taskInfo.getType() == eTaskType.Main.getValue() ||
                (taskInfo.getType() == eTaskType.Achievement.getValue() && taskInfo.getNextTaskId() > 0) ||
                (taskInfo.getType() == eTaskType.GrandChildExamTask.getValue() && taskInfo.getNextTaskId() > 0) ||
                (taskInfo.getType() == eTaskType.DrugStoreChuFangLevel.getValue() && taskInfo.getNextTaskId() > 0) ||
                (taskInfo.getType() == eTaskType.KowloonHero.getValue() && taskInfo.getNextTaskId() > 0) ||
                (taskInfo.getType() == eTaskType.Kuang.getValue() && taskInfo.getNextTaskId() > 0) ||
                //(taskInfo.getType() == eTaskType.CurioScoreTask.getValue() && taskInfo.getNextTaskId() > 0) ||
                (taskInfo.getType() == eTaskType.SpecialCookBoyPassLevelNum.getValue() && taskInfo.getNextTaskId() > 0) ||
                (taskInfo.getType() == eTaskType.MusicRoom.getValue() && taskInfo.getNextTaskId() > 0) ||
                (taskInfo.getType() == eTaskType.IceServerMainTask.getValue() && taskInfo.getNextTaskId() > 0) ||
                (taskInfo.getType() == eTaskType.IceServerSubTask.getValue() && taskInfo.getNextTaskId() > 0)
        ) {
            showBaseTaskDataMap.remove(baseTaskData.getUserTaskData().getTaskId());
        }

        int nextTaskId = taskInfo.getNextTaskId();
        msg.setRet(0);
        msg.setFinishTime(baseTaskData.getUserTaskData().getFinishTime());
        msg.setNextTaskId(nextTaskId);
        BaseTaskData nextQuest = null;
        if (nextTaskId > 0) {
            //同步任务给客户端
            TaskInfo nextTaskInfo = TaskMgr.getTaskInfoById(nextTaskId);
            if (nextTaskInfo != null) {
                addTask(nextTaskInfo);
            }
            nextQuest = baseTaskDataMap.get(nextTaskId);
            showBaseTaskDataMap.put(nextTaskId, nextQuest);
            changeValue(nextQuest);
        }
        finishChanges();
        if(nextTaskId > 0){
            if(null != nextQuest){
                msg.setNextTask(TaskPb.parseTaskDataTempMsg(nextQuest.getTaskId(), nextQuest.getUserTaskData()));
            }
        }
        //判断系统开放
        if (taskInfo.getType() == eTaskType.Main.getValue()) {
            player.getModule(PlayerModule.class).checkSystemOpen();
            //小当家特色服判断关卡解锁
            player.getModule(SpecialCookBoyModule.class).checkLevelUnlock();
        }else if(taskInfo.getType() == eTaskType.Daily.getValue()){
            attributeModule.addAttribute(ePlayerAttrType.TotalDailyTaskFinishTimes, 1);
            player.notifyListener(eGamePlayerEventType.DailyTaskTotalFinishTimes.getValue(), attributeModule.getAttribute(ePlayerAttrType.TotalDailyTaskFinishTimes));
        }
        //主线、支线、日常、周常
        DataAnalyticsMgr.trackTaskCompleteAndGetReward(player, taskInfo);
        if(taskInfo.getType() == eTaskType.GrandChildExamTask.getValue()){
            //GrandChildLog.genealogyAchievement(player, taskInfo, baseTaskData);
        }
        return msg;
    }
    //只支持财神密卷和日常任务的一键
    public TaskProto.TaskGetRewardRespMsg.Builder getTaskRewards(List<Integer> taskIdList){
        TaskProto.TaskGetRewardRespMsg.Builder msg = TaskProto.TaskGetRewardRespMsg.newBuilder();
        msg.setNextTaskId(0);
        int titleId = player.getUserInfo().getTitleId();
        for(int taskId : taskIdList){
            BaseTaskData baseTaskData = baseTaskDataMap.get(taskId);
            // 判断该任务是否完成
            if(null == baseTaskData){
                msg.setRet(GameErrorCode.E_TASK_NO_FOUND);
                return msg;
            }
            if (baseTaskData.getUserTaskData() == null) {
                // 初始化一下
                baseTaskData.initUserTaskData();
            }
            TaskInfo taskInfo = TaskMgr.getTaskInfoById(taskId);
            if(null == taskInfo){
                msg.setRet(GameErrorCode.E_TASK_NO_FOUND);
                return msg;
            }
            if(taskInfo.getType() == eTaskType.Daily.getValue()){
                if(titleId < GameConfig.TASK_DAILY_ACTIVE_GET_ALL_REWARD_NEED_LV){
                    msg.setRet(GameErrorCode.E_TASK_ONEKEY_LV_LIMIT_DAILY);
                    return msg;
                }
            }
            if(taskInfo.getType() == eTaskType.SecretVolumeTask.getValue() || taskInfo.getType() == eTaskType.SecretVolumeLevel.getValue()){
                if(titleId < GameConfig.SECRET_VOLUME_GET_ALL_REWARD_NEED_LV){
                    msg.setRet(GameErrorCode.E_TASK_ONEKEY_LV_LIMIT_SECRET_VOLUME);
                    return msg;
                }
            }

            if(baseTaskData.getUserTaskData().getState() == 1){
                msg.setRet(GameErrorCode.E_TASK_ALREADY_GET_REWARD);
                return msg;
            }
            if(!baseTaskData.canCompleted()) {
                msg.setRet(GameErrorCode.E_TASK_NOT_COMPLETE);
                return msg;
            }
            if (taskInfo.getType() != eTaskType.Daily.getValue() &&
                    taskInfo.getType() != eTaskType.SecretVolumeTask.getValue() &&
                    taskInfo.getType() != eTaskType.SecretVolumeLevel.getValue() &&
                    taskInfo.getType() != eTaskType.Cricket.getValue() &&
                    taskInfo.getType() != eTaskType.KowloonHero.getValue() &&
                    taskInfo.getType() != eTaskType.Kuang.getValue()&&
                    taskInfo.getType() != eTaskType.CurioScoreTask.getValue()&&
                    taskInfo.getType() != eTaskType.SpecialCookBoyPassLevelNum.getValue() &&
                    taskInfo.getType() != eTaskType.WeekendSystem.getValue() &&
                    taskInfo.getType() != eTaskType.DrugStoreChuFangLevel.getValue() &&
                    taskInfo.getType() != eTaskType.MusicRoom.getValue() &&
                    taskInfo.getType() != eTaskType.IceServerMainTask.getValue() &&
                    taskInfo.getType() != eTaskType.IceServerSubTask.getValue()) {
                msg.setRet(GameErrorCode.E_TASK_ONEKEY_NO_SUPPORT);
                return msg;
            }
        }
        msg.setRet(0);
        boolean isDailyNotice = false;
        AttributeModule attributeModule = player.getModule(AttributeModule.class);
        startChanges();
        for(int taskId : taskIdList){
            // 判断该任务是否完成
            BaseTaskData baseTaskData = baseTaskDataMap.get(taskId);
            TaskInfo taskInfo = TaskMgr.getTaskInfoById(taskId);
            baseTaskData.finish();
            if(taskInfo.getType() == eTaskType.Daily.getValue()){
                isDailyNotice = true;
                attributeModule.addAttribute(ePlayerAttrType.TotalDailyTaskFinishTimes, 1);
            }
            //主线、支线、日常、周常
            DataAnalyticsMgr.trackTaskCompleteAndGetReward(player, taskInfo);
        }
        finishChanges();

        if(isDailyNotice){
            player.notifyListener(eGamePlayerEventType.DailyTaskTotalFinishTimes.getValue(), attributeModule.getAttribute(ePlayerAttrType.TotalDailyTaskFinishTimes));
        }

        return msg;
    }

    /**
     * 领取活跃奖励
     */
    public int getTaskActiveReward(int taskActive) {
        if (userTaskActive.getTaskGetRewardIndexList().contains(taskActive)) {
            return GameErrorCode.E_TASK_ALREADY_GET_REWARD;
        }
        int index = ConfigMgr.getTaskDailyActiveIndex(taskActive);
        if (-1 == index) {
            return GameErrorCode.E_TASK_ACTIVE_NO_MATCH;
        }
        if (userTaskActive.getTaskActive() >= taskActive) {
            Property reward = ConfigMgr.getTaskDailyActiveReward(index);
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.Task, eLogMoneyType.TaskGetDailyActiveReward);
            userTaskActive.addRewadIndex(taskActive);
            syncTaskActive();// 同步修改后的积分
            LogMgr.addLogTaskActiveReward(player.getUserId(), taskActive, index, PropertyHelper.parsePropertyToString(reward), false);
            return 0;
        } else {
            return GameErrorCode.E_TASK_ACTIVE_NO_ENOUGH;
        }
    }

    public int getSevenDayActiveReward(int taskActive) {
        if(getSevenDayOffsetDays() > 8){
            return GameErrorCode.E_TASK_SEVEN_DAY_OVER_NO_REWARD;
        }
        if (userTaskActive.getSevenDayGetRewardIndexList().contains(taskActive)) {
            return GameErrorCode.E_TASK_ALREADY_GET_REWARD;
        }
        int index = ConfigMgr.getSevenDayActiveIndex(taskActive);
        if (-1 == index) {
            return GameErrorCode.E_TASK_ACTIVE_NO_MATCH;
        }
        if (userTaskActive.getSevenDayActive() >= taskActive) {
            Property reward = ConfigMgr.getSevenDayActiveReward(index);
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.Task, eLogMoneyType.TaskGetSevenDayActiveReward);
            userTaskActive.addSevenRewardIndex(taskActive);
            syncSevenDayActive();// 同步修改后的积分
            LogMgr.addLogTaskActiveReward(player.getUserId(), taskActive, index, PropertyHelper.parsePropertyToString(reward), true);
            return 0;
        } else {
            return GameErrorCode.E_TASK_ACTIVE_NO_ENOUGH;
        }
    }

    public int getSevenDayOffsetDays(){
        return DateHelper.calc2DateTDOADays(new Date(userTaskActive.getSevenDayStartTime() * 1000), new Date());
    }

    /**
     * 开始变更，变一下标识
     */
    public void startChanges() {
        changeCount.getAndIncrement();
    }

    /**
     * 变更完成
     */
    public void finishChanges() {
        synchronized (changeCount) {
            int changes = changeCount.decrementAndGet();
            if (changes < 0) {
                log.error("not exce startChanges" + new Error());
                changeCount.set(0);
            }
            if (changes <= 0 && changedBaseTaskDataList.size() > 0) {
                updateChangedTaskList();
            }

            updateChangedObjectTaskList();
        }
    }

    private boolean canComplete(int taskId) {
        BaseTaskData baseTaskData = baseTaskDataMap.get(taskId);
        if (null != baseTaskData && baseTaskData.getUserTaskData() != null) {
            return baseTaskData.getUserTaskData().getState() == 0 && baseTaskData.canCompleted();
        }
        return false;
    }

    private void addTaskFromUserTaskData(UserTaskData userTaskData) {
        if(null == userTaskData){
            return;
        }
        TaskInfo taskInfo = TaskMgr.getTaskMap().get(userTaskData.getTaskId());
        if(null == taskInfo){
            return;
        }
        if (taskInfo.getType() == eTaskType.Daily.getValue() || taskInfo.getType() == eTaskType.SevenDay.getValue() || userTaskData.getState() == 0 ||
                (taskInfo.getType() == eTaskType.Achievement.getValue() && taskInfo.getNextTaskId() == 0 && userTaskData.getState() == 1) ||
                taskInfo.getType() == eTaskType.Beauty.getValue() || userTaskData.getTaskType() == eTaskType.MammonDecorationCount.getValue() ||
                taskInfo.getType() == eTaskType.SecretVolumeLevel.getValue() || taskInfo.getType() == eTaskType.SecretVolumeTask.getValue() ||
                taskInfo.getType() == eTaskType.WingRoomUnLock.getValue() || taskInfo.getType() == eTaskType.MammonShopWakeupTask.getValue() ||
                (taskInfo.getType() == eTaskType.Cricket.getValue() && taskInfo.getNextTaskId() == 0 && userTaskData.getState() == 1) ||
                (taskInfo.getType() == eTaskType.KowloonHero.getValue() && taskInfo.getNextTaskId() == 0 && userTaskData.getState() == 1) ||
                (taskInfo.getType() == eTaskType.Kuang.getValue() && taskInfo.getNextTaskId() == 0 && userTaskData.getState() == 1) ||
                (taskInfo.getType() == eTaskType.DrugStoreChuFangLevel.getValue() && taskInfo.getNextTaskId() == 0 && userTaskData.getState() == 1) ||
                (taskInfo.getType() == eTaskType.GrandChildExamTask.getValue() && taskInfo.getNextTaskId() == 0 && userTaskData.getState() == 1)||
                (taskInfo.getType() == eTaskType.SpecialCookBoyPassLevelNum.getValue() && taskInfo.getNextTaskId() == 0 && userTaskData.getState() == 1) ||
                taskInfo.getType() == eTaskType.WeekendSystem.getValue() ||
                taskInfo.getType() == eTaskType.CurioScoreTask.getValue() ||
                (taskInfo.getType() == eTaskType.MusicRoom.getValue() && taskInfo.getNextTaskId() == 0 && userTaskData.getState() == 1) ||
                taskInfo.getType() == eTaskType.ALiPayTask.getValue() ||
                taskInfo.getType() == eTaskType.MeiTuanTask.getValue() ||
                taskInfo.getType() == eTaskType.ALiPayFiveBlessingsTask.getValue() ||
                (taskInfo.getType() == eTaskType.IceServerMainTask.getValue() && taskInfo.getNextTaskId() == 0 && userTaskData.getState() == 1) ||
                (taskInfo.getType() == eTaskType.IceServerSubTask.getValue() && taskInfo.getNextTaskId() == 0 && userTaskData.getState() == 1)
        ){
            BaseTaskData baseTaskData = new BaseTaskData(null, userTaskData, player);

            TaskConditionInfo taskCondition = TaskMgr.getTaskConditionById(userTaskData.getTaskId());
            if (null == taskCondition) {
                return;
            }
            BaseCondition baseCondition = BaseCondition.createCondition(player, baseTaskData, taskCondition, userTaskData.getValue());
            if (null != baseCondition) {
                baseCondition.setValue(userTaskData.getValue());
                baseTaskData.setBaseCondition(baseCondition);
            }

            baseTaskData.playerAddTrigger(player);
            baseTaskDataMap.put(userTaskData.getTaskId(), baseTaskData);
            addShowTaskData(baseTaskData);
        }
    }

    /**
     * 增加已开放的任务
     */
    public void addTask(TaskInfo taskInfo) {
        Date nowDate = new Date();
        if (taskInfo.getBeginTime().compareTo(nowDate) < 0 && taskInfo.getEndTime().compareTo(nowDate) > 0) {
            if (baseTaskDataMap.get(taskInfo.getTaskId()) == null) {
                UserTaskData preUserTaskData = null;
                if (baseTaskDataMap.containsKey(taskInfo.getPreTaskId())) {
                    preUserTaskData = baseTaskDataMap.get(taskInfo.getPreTaskId()).getUserTaskData();
                }

                if (taskInfo.getType() == eTaskType.Achievement.getValue() ||
                        taskInfo.getType() == eTaskType.GrandChildExamTask.getValue() ||
                        taskInfo.getType() == eTaskType.DrugStoreChuFangLevel.getValue() ||
                        taskInfo.getType() == eTaskType.Kuang.getValue() ||
                        taskInfo.getType() == eTaskType.KowloonHero.getValue() ||
                        taskInfo.getType() == eTaskType.SpecialCookBoyPassLevelNum.getValue() ||
                        taskInfo.getType() == eTaskType.MusicRoom.getValue() ||
                        taskInfo.getType() == eTaskType.IceServerMainTask.getValue() ||
                        taskInfo.getType() == eTaskType.IceServerSubTask.getValue()
                ) {
                    UserTaskData userTaskData = getUserTaskData(taskInfo.getPreTaskId());
                    if (userTaskData == null) {
                        userTaskData = preUserTaskData;
                    }
                    if (taskInfo.getPreTaskId() == 0 || ((userTaskData != null) && userTaskData.getState() == 1)) {
                        listenTaskTrigger(taskInfo, userTaskData);
                    }
                } else {
                    listenTaskTrigger(taskInfo, null);
                }
            }
        }
    }

    /**
     * 监听任务触发
     */
    private void listenTaskTrigger(TaskInfo taskInfo, UserTaskData preTaskData) {
        if (taskInfo.getType() == eTaskType.Main.getValue()) {
            if (taskInfo.getTaskId() < curMainTaskId) {
                curMainTaskId = taskInfo.getTaskId();
                realMainTaskId = curMainTaskId;
            } else {
                return;
            }
        } else if (taskInfo.getType() == eTaskType.SevenDay.getValue()) {
            int days = getSevenDayOffsetDays();
            if (taskInfo.getLittleType() > days || days > 8) {
                return;
            }
        }

//        UserTaskData taskData = initUserTaskData(taskInfo);
        int questId = taskInfo.getTaskId();

//        BaseTaskData baseTaskData = new BaseTaskData(null, taskData, player);
        BaseTaskData baseTaskData = new BaseTaskData(player, questId);

        //判断他的默认值
        TaskConditionInfo taskCondition = TaskMgr.getTaskConditionById(questId);
        if (taskCondition == null) {
            return;
        }

        addShowTaskData(baseTaskData);
        baseTaskDataMap.put(questId, baseTaskData);

        BaseCondition condition = BaseCondition.createCondition(player, baseTaskData, taskCondition, BigInteger.ZERO);
        if (condition != null) {
            baseTaskData.setBaseCondition(condition);
        }

        //成就先导入之前的成就值
        if (null != preTaskData) {
            baseTaskData.retainData(preTaskData);
        }

        // 主线任务重新开始计算条件
        if(null != condition){
            condition.initValue();
        }

        baseTaskData.playerAddTrigger(player);
    }

    private void addShowTaskData(BaseTaskData baseTaskData) {
        if (getShowBaseTaskDataMap().containsKey(baseTaskData.getTaskId())) {
            return;
        }
        TaskInfo taskInfo = TaskMgr.getTaskInfoById(baseTaskData.getTaskId());
        if (taskInfo == null) {
            return;
        }
        UserTaskData userTaskData = baseTaskData.getUserTaskData();

        // 成就等类型已领奖的只有最后一条才会下发
        if (userTaskData != null && (
                userTaskData.getTaskType() == eTaskType.Achievement.getValue() ||
                        userTaskData.getTaskType() == eTaskType.Cricket.getValue() ||
                        userTaskData.getTaskType() == eTaskType.KowloonHero.getValue() ||
                        userTaskData.getTaskType() == eTaskType.Kuang.getValue() ||
                        userTaskData.getTaskType() == eTaskType.DrugStoreChuFangLevel.getValue() ||
                        userTaskData.getTaskType() == eTaskType.GrandChildExamTask.getValue() ||
                        userTaskData.getTaskType() == eTaskType.SpecialCookBoyPassLevelNum.getValue() ||
                        userTaskData.getTaskType() == eTaskType.MusicRoom.getValue() ||
                        userTaskData.getTaskType() == eTaskType.IceServerMainTask.getValue() ||
                        userTaskData.getTaskType() == eTaskType.IceServerSubTask.getValue()
        )
                && userTaskData.getState() == 1 && taskInfo.getNextTaskId() != 0) {
            return;
        }

        if (taskInfo.getPreTaskId() == 0) {
            getShowBaseTaskDataMap().put(taskInfo.getTaskId(), baseTaskData);
        } else if (isSecretVolumeTask(taskInfo)) {
            getShowBaseTaskDataMap().put(taskInfo.getTaskId(), baseTaskData);
        } else if(taskInfo.getType() == eTaskType.CurioScoreTask.getValue()){
            getShowBaseTaskDataMap().put(taskInfo.getTaskId(), baseTaskData);
        } else {
            // 有前置任务的判断下前置任务是否完成
            BaseTaskData preQuest = baseTaskDataMap.get(taskInfo.getPreTaskId());
            UserTaskData userLastTask;
            if (null != preQuest) {
                userLastTask = preQuest.getUserTaskData();
            } else {
                userLastTask = getUserTaskData(taskInfo.getPreTaskId());
            }
            if (userLastTask != null && userLastTask.getState() == 1) {
                getShowBaseTaskDataMap().put(taskInfo.getTaskId(), baseTaskData);
            }
        }
    }

    private boolean isSecretVolumeTask(TaskInfo taskInfo){
        return taskInfo.getType() == eTaskType.SecretVolumeTask.getValue() ||
                taskInfo.getType() == eTaskType.SecretVolumeLevel.getValue();
    }

    //厢房解锁任务是否都完成
    public boolean wingRoomUnlockTaskAllFinish() {
        boolean hasTask = false;
        if (baseTaskDataMap != null) {
            for (BaseTaskData taskData : baseTaskDataMap.values()) {
                if (taskData.getUserTaskData() == null) {
                    continue;
                }
                if (taskData.getUserTaskData().getTaskType() == eTaskType.WingRoomUnLock.getValue()) {
                    hasTask = true;
                    if (taskData.getUserTaskData().getState() == 0) {
                        return false;
                    }
                }
            }
        }
        return hasTask;
    }

    public int getRealMainTaskId() {
        return realMainTaskId;
    }

    public UserTaskData initUserTaskData(TaskInfo taskInfo) {
        Date taskDate;
        if (taskInfo.getType() == eTaskType.Daily.getValue()
        || taskInfo.getType() == eTaskType.WeekendSystem.getValue()) {//周末的成就也是每日重置的
            taskDate = DateHelper.getDate0AM(new Date());
        } else {
            taskDate = DateHelper.getDate(2050, 1, 1, 1, 1, 1);
        }
        UserTaskData taskData = new UserTaskData();
        taskData.setUserId(player.getUserId());
        taskData.setTaskId(taskInfo.getTaskId());
        taskData.setTaskType(taskInfo.getType());
        taskData.setState(0);
        taskData.setPreTaskId(taskInfo.getPreTaskId());
        taskData.setStartTime(new Date());
        taskData.setEndTime(taskDate);
        taskData.setInsertOption();
        return taskData;
    }

    /**
     * 重置每日活跃度
     */
    public void resetActive() {
        if(null == userTaskActive) {
            return;
        }
        synchronized (userTaskActive) {
            long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
            if (userTaskActive.getLastUpdateTime() < zeroTime) {
                userTaskActive.setLastUpdateTime(zeroTime);
                userTaskActive.setTaskActive(0);
                userTaskActive.setTaskGetRewardIndexList(new ArrayList<>());
            }
        }
    }

    /**
     * 重置日常任务
     */
    public void resetOneDay() {
        boolean isReset = false;
        Map<String, TaskConditionMail> needSendMailMap = new HashMap<>();
        // 如果是日常任务的话 把过时的日期设置为当天 并初始化任务状态
        Map<Integer, BaseTaskData> map = new HashMap<>(baseTaskDataMap);
        for (BaseTaskData baseTaskData : map.values()) {
            UserTaskData userTaskData = baseTaskData.getUserTaskData();
            if (userTaskData == null) {
                continue;
            }
            if (baseTaskData.getBaseCondition() == null) {
                continue;
            }
            if (baseTaskData.isNeedDayReset() && baseTaskData.isResetDailyTask()) {
                if (baseTaskData.getBaseCondition().isNeedAutoSendMail() && baseTaskData.canCompleted()) {
                    String mailKey = baseTaskData.getBaseCondition().getMailKey();
                    TaskConditionMail taskConditionMail = needSendMailMap.get(mailKey);
                    if (taskConditionMail == null) {
                        taskConditionMail = baseTaskData.getBaseCondition().newConditionMail();
                        needSendMailMap.put(mailKey, taskConditionMail);
                    }
                    if (taskConditionMail != null) {
                        TaskInfo taskInfo = TaskMgr.getTaskInfoById(userTaskData.getTaskId());
                        taskConditionMail.addProperty(taskInfo.getReward());
                    } else {
                        log.error("resetOneDay taskConditionMail is null, player = {}, taskId={}", player.getUserId(), userTaskData.getTaskId());
                    }
                }

                baseTaskData.resetDailyTask();
                isReset = true;
            }

        }

        if (!needSendMailMap.isEmpty()) {
            for (TaskConditionMail taskConditionMail : needSendMailMap.values()) {
                MailManager.sendMail(player.getUserId(), eMailType.SYSTEM.getValue(), taskConditionMail.getRewardStr(), taskConditionMail.getMailContent(), taskConditionMail.getMailTitle());
            }
        }

        if (isReset) {
            resetActive();
            syncTaskActive();
        }
    }

    /**
     * 每周一個節點重置密卷活動，遇到不滿一周但是檔期結束的時候也要重置
     * @param force boolean 强制重置
     */
    public void resetSecretVolumeSevenDay(boolean force) {
        boolean isReset = false;
        // 如果是密卷任务的话 把过时的日期设置为七天之后 并初始化任务状态
        Map<Integer, BaseTaskData> map = new HashMap<>(baseTaskDataMap);
        for (BaseTaskData baseTaskData : map.values()) {
            UserTaskData userTaskData = baseTaskData.getUserTaskData();
            if (userTaskData == null) {
                continue;
            }
            if (userTaskData.getTaskType() == eTaskType.SecretVolumeTask.getValue()) {
                if (baseTaskData.isResetWeekTask() || force) {
                    baseTaskData.resetWeekTask(force);
                    isReset = true;
                }
            }
        }
        //没有同步逻辑
        if(isReset){

        }
    }

    /**
     * 重置密卷等級
     * @param time 上一次的等級的开始时间
     * @param newDay 這一次新的的等級
     */
    public void resetSecretVolumeLevel(long time,int newDay) {
        boolean isReset = false;
        // 如果是密卷任务的话 把过时的日期设置为一期28天之后 并初始化任务状态
        Map<Integer, BaseTaskData> map = new HashMap<>(baseTaskDataMap);
        for (BaseTaskData baseTaskData : map.values()) {
            UserTaskData userTaskData = baseTaskData.getUserTaskData();
            if (userTaskData == null) {
                continue;
            }
            if (userTaskData.getTaskType() == eTaskType.SecretVolumeLevel.getValue()) {
                if (baseTaskData.isResetCustomTask(time,newDay)) {
                    baseTaskData.resetCustomTask(time,newDay);
                    isReset = true;
                }
            }
        }
        //没有同步逻辑
        if(isReset){

        }
    }

    /**
     * 重置矿场成就
     *
     * @return
     */
    public void resetKuangAchieve() {
        boolean isReset = false;
        Map<Integer, BaseTaskData> map = new HashMap<>(baseTaskDataMap);
        for (BaseTaskData baseTaskData : map.values()) {
            UserTaskData userTaskData = baseTaskData.getUserTaskData();
            if (userTaskData == null) {
                continue;
            }
            if (userTaskData.getTaskType() == eTaskType.Kuang.getValue()) {
                baseTaskData.resetKuangTask();
                isReset = true;
            }
        }
        //没有同步逻辑
        if(isReset){

        }
    }

    public Map<Integer, BaseTaskData> getBaseTaskDataMap() {
        return baseTaskDataMap;
    }

    public void checkSevenDayTask() {
        for (TaskInfo info : TaskMgr.getTaskMap().values()) {
            if (info.getType() == eTaskType.SevenDay.getValue() && !baseTaskDataMap.containsKey(info.getTaskId()) && !userTaskDataMap.containsKey(info.getTaskId())) {
                addTask(info);
                BaseTaskData baseTaskData = baseTaskDataMap.get(info.getTaskId());
                if(null != baseTaskData){
                    changeValue(baseTaskData);
                }
            }
        }

        // 如果时间超过七天 删除七日活动的事件监听
        if (getSevenDayOffsetDays() > 8) {
            for (BaseTaskData quest : baseTaskDataMap.values()) {
                if (quest.getUserTaskData() == null) {
                    continue;
                }
                if (quest.getUserTaskData().getTaskType() == eTaskType.SevenDay.getValue()) {
                    quest.removeTrigger();
                }
            }
        }
    }

    //新增家具目标任务
    public void addWingRoomUnLockTask() {
        for (TaskInfo info : TaskMgr.getTaskMap().values()) {
            if (info.getType() == eTaskType.WingRoomUnLock.getValue() && !baseTaskDataMap.containsKey(info.getTaskId()) && !userTaskDataMap.containsKey(info.getTaskId())) {
                addTask(info);
            }
        }
        syncUserTaskData();
    }

    public void addMusicRoomUnlockTask() {
        for (TaskInfo info : TaskMgr.getTaskMap().values()) {
            if (info.getType() == eTaskType.MusicRoom.getValue() && !baseTaskDataMap.containsKey(info.getTaskId()) && !userTaskDataMap.containsKey(info.getTaskId())) {
                addTask(info);
            }
        }
        syncUserTaskData();
    }

    public void addMammonUnlockTask() {
        for (TaskInfo info : TaskMgr.getTaskMap().values()) {
            if (info.getType() == eTaskType.MammonDecorationCount.getValue() && !baseTaskDataMap.containsKey(info.getTaskId()) && !userTaskDataMap.containsKey(info.getTaskId())) {
                addTask(info);
            }
        }
        syncUserTaskData();
    }


    public IEvent getGameEvent() {
        return gameEvent;
    }

    public UserTaskData getUserTaskData(int taskId) {
        return userTaskDataMap.get(taskId);
    }

    private Map<Integer, BaseTaskData> getShowBaseTaskDataMap() {
        return showBaseTaskDataMap;
    }

    public final void changeValue(BaseTaskData quest) {
        if (null != quest) {
            onTaskChanged(quest);
        }
    }

    /**
     * 任务变更
     */
    private void onTaskChanged(BaseTaskData baseTaskData) {
        if (null == baseTaskData) {
            return;
        }
        if (!changedBaseTaskDataList.contains(baseTaskData)) {
            synchronized (changedBaseTaskDataList) {
                changedBaseTaskDataList.add(baseTaskData);
            }
        }

        if (changeCount.intValue() <= 0 && changedBaseTaskDataList.size() > 0 || changedBaseTaskDataList.size() > 20) {
            updateChangedTaskList();
        }
    }

    /**
     * 变更下发给客户端
     */
    private void updateChangedTaskList() {
        if (changedBaseTaskDataList.size() > 0) {
            List<BaseTaskData> changedList;
            synchronized (changedBaseTaskDataList) {
                changedList = new ArrayList<>(changedBaseTaskDataList);
                changedBaseTaskDataList.clear();
            }
            syncChangedTask(changedList);
        }
    }

    private void syncChangedTask(List<BaseTaskData> baseTaskDataList) {
        if (null == baseTaskDataList) {
            return;
        }
        TaskProto.TaskDataListMsg.Builder listMsg = TaskProto.TaskDataListMsg.newBuilder();
        for(BaseTaskData baseTaskData : baseTaskDataList){
            TaskInfo taskInfo = TaskMgr.getTaskMap().get(baseTaskData.getTaskId());
            if(null == taskInfo){
                log.info("not task {}", baseTaskData.getTaskId());
                continue;
            }
            listMsg.addDataList(TaskPb.parseTaskDataTempMsg(baseTaskData.getTaskId(), baseTaskData.getUserTaskData()));
        }
        player.sendPacket(Protocol.U_TASK_DATA_SYNC, listMsg);
    }

    /**
     * 跳转至指定主线任务,完成taskId-1的任务
     * @param taskId
     */
    public int jumpToMainTask(int taskId){
        TaskInfo jumpToTaskInfo = TaskMgr.getTaskInfoById(taskId);
        if(jumpToTaskInfo == null){
            return -1;
        }
        if(jumpToTaskInfo.getType() != eTaskType.Main.getValue()){
            return -1;
        }
        if(taskId <= realMainTaskId){
            return -1;
        }
        TaskInfo next = TaskMgr.getTaskInfoById(this.realMainTaskId);
        BaseTaskData baseTaskData;
        startChanges();
        while(next != null && next.getNextTaskId() > 0 && next.getTaskId() != taskId){
            baseTaskData = baseTaskDataMap.get(next.getTaskId());
            if(null == baseTaskData){
                UserTaskData taskData = initUserTaskData(next);
                int questId = next.getTaskId();
                baseTaskData = new BaseTaskData(null, taskData, player);
                //判断他的默认值
                TaskConditionInfo taskCondition = TaskMgr.getTaskConditionById(questId);
                if (taskCondition == null) {
                    return -1;
                }
                baseTaskDataMap.put(questId, baseTaskData);
                BaseCondition condition = BaseCondition.createCondition(player, baseTaskData, taskCondition, BigInteger.ZERO);
                if (condition != null) {
                    baseTaskData.setBaseCondition(condition);
                }
                // 主线任务重新开始计算条件
                if(null != condition){
                    condition.initValue();
                }
            }else{
                showBaseTaskDataMap.remove(baseTaskData.getUserTaskData().getTaskId());
            }
            baseTaskData = baseTaskDataMap.get(next.getTaskId());
            baseTaskData.finish();
            next = TaskMgr.getTaskInfoById(next.getNextTaskId());
        }
        if( null != next){
            this.curMainTaskId = Integer.MAX_VALUE;
            addTask(next);
            baseTaskData = baseTaskDataMap.get(next.getTaskId());
            showBaseTaskDataMap.put(next.getTaskId(), baseTaskData);
            changeValue(baseTaskData);
        }
        syncUserTaskData();
        finishChanges();
        return 0;
    }


    public Property recoveryDailyTaskReward(int days, int discount) {
        Property finalReward = new Property();
        Map<Integer, BaseTaskData> map = new HashMap<>(baseTaskDataMap);
        for (BaseTaskData baseTaskData : map.values()) {
            UserTaskData userTaskData = baseTaskData.getUserTaskData();
            if (userTaskData == null) {
                continue;
            }
            if (userTaskData.getTaskType() == eTaskType.Daily.getValue()){
                TaskInfo taskInfoById = TaskMgr.getTaskInfoById(userTaskData.getTaskId());
                if (taskInfoById != null) {
                    finalReward.addProperty(taskInfoById.getReward());
                }
            }
        }
        int param = days * discount / 1000;
        finalReward.goodCountMultiNum(param);
        player.getModule(CurrencyModule.class).addCurrency(finalReward, eLogMoneyType.RecoveryReward, eLogMoneyType.RecoveryDailyTaskIngots);
        return finalReward;
    }

    public UserTaskActive getUserTaskActive() {
        return userTaskActive;
    }


    public IObjectEvent getGameObjectEvent() {
        return gameObjectEvent;
    }

    /**
     * 读数据库
     */
    public void loadObjectTaskDb() {
        List<UserObjectTaskData> tempList = new UserCommonActivityDataDaoImpl<UserObjectTaskData>().getUserDataList(UserObjectTaskData.class, getUserId());
        Map<Integer, Map<Integer, UserObjectTaskData>> tempDataMap = new ConcurrentHashMap<>();
        for (UserObjectTaskData userObjectTaskData : tempList) {
            Map<Integer, UserObjectTaskData> dataMap = tempDataMap.get(userObjectTaskData.getCompleteType());
            if (dataMap == null) {
                dataMap = new ConcurrentHashMap<>();
                tempDataMap.put(userObjectTaskData.getCompleteType(), dataMap);
            }
            dataMap.put(userObjectTaskData.getObjectId(), userObjectTaskData);
        }
        this.userObjectTaskDataMap = tempDataMap;
    }

    /**
     * 装载任务监听
     *
     * @param dataMap
     */
    public void loadObjectTaskCondition(Map<Integer, Map<Integer, UserObjectTaskData>> dataMap) {
        Map<Integer, List<Integer>> objectTaskIdMap = TaskMgr.getObjectTaskIdMap();
        for (Map.Entry<Integer, List<Integer>> entry : objectTaskIdMap.entrySet()) {
            int completeType = entry.getKey();
            List<Integer> taskIds = entry.getValue();
            Map<Integer, UserObjectTaskData> taskDataMap = dataMap.get(completeType);
            BaseObjectCondition condition = BaseObjectCondition.createCondition(player, completeType, taskIds, taskDataMap);
            if (condition == null) {
                continue;
            }
            condition.addTrigger(player);
        }
    }

    /**
     * 旧任务数据转换为新的指定对象任务
     */
    public void transformOldTaskDataToObjectTask() {
        Map<Integer, UserTaskData> filterMap = new ConcurrentHashMap<>();

        for (UserTaskData userTaskData : userTaskDataMap.values()) {
            if (OldTaskChangeMgr.isNeedTransformTask(userTaskData.getTaskType())) {
                OldTaskChangeConfigData oldTaskChangeConfig = OldTaskChangeMgr.getOldTaskChangeConfig(userTaskData.getTaskId());
                if (oldTaskChangeConfig == null) {
                    continue;
                }
                TaskConditionInfo taskConditionById = TaskMgr.getTaskConditionById(oldTaskChangeConfig.getNewId());
                if (taskConditionById == null) {
                    continue;
                }
                int objectId = oldTaskChangeConfig.getObjectId();
                int completeType = taskConditionById.getType();

                userTaskData.setDelete(true);
                synchronized (waitSaveDataList) {
                    waitSaveDataList.add(userTaskData);
                }

                if (userTaskData.getState() == 1) {
                    UserObjectTaskData userObjectTaskData = getObjectTaskDataNewIfNull(objectId, completeType);
                    userObjectTaskData.addFinishTaskId(oldTaskChangeConfig.getNewId());
                }

                //如果有需要进度值的就更新最大进度值
            } else {
                filterMap.put(userTaskData.getTaskId(), userTaskData);
            }
        }
        userTaskDataMap = filterMap;
    }

    /**
     * 同步全部任务
     */
    private void syncUserObjectTaskData() {
        ObjectTaskProto.ObjectTaskDataListMsg.Builder listMsg = ObjectTaskProto.ObjectTaskDataListMsg.newBuilder();
        for (Map<Integer, UserObjectTaskData> dataMap : userObjectTaskDataMap.values()) {
            for (UserObjectTaskData data : dataMap.values()) {
                listMsg.addDataList(TaskPb.parseObjectTaskDataTempMsg(data));
            }
        }
        player.sendPacket(Protocol.S_OBJECT_TASK_DATA_SEND % 20000, listMsg);
    }

    private void syncChangedObjectTask(List<UserObjectTaskData> dataList) {
        if (null == dataList || dataList.isEmpty()) {
            return;
        }
        ObjectTaskProto.ObjectTaskDataListMsg.Builder syncMsg = TaskPb.parseObjectTaskDataListMsg(dataList);
        player.sendPacket(Protocol.S_OBJECT_TASK_DATA_SYNC % 20000, syncMsg);
    }

    public void objectTaskChange(UserObjectTaskData taskData) {
        if (objectTaskChangeSet.contains(taskData)) {
            return;
        }
        synchronized (objectTaskChangeSet) {
            objectTaskChangeSet.add(taskData);
        }

        if (changeCount.intValue() <= 0 && objectTaskChangeSet.size() > 0 || objectTaskChangeSet.size() > 20) {
            updateChangedObjectTaskList();
        }
    }

    /**
     * 变更下发给客户端
     */
    private void updateChangedObjectTaskList() {
        if (objectTaskChangeSet.size() > 0) {
            List<UserObjectTaskData> changedList;
            synchronized (objectTaskChangeSet) {
                changedList = new ArrayList<>(objectTaskChangeSet);
                objectTaskChangeSet.clear();
            }
            syncChangedObjectTask(changedList);
        }
    }

    public int getObjectTaskReward(ObjectTaskProto.ObjectTaskGetRewardReqMsg reqMsg) {
        if (reqMsg.getCompletesList().isEmpty()) {
            return GameErrorCode.E_ERROR_PARAMETER;
        }
        int ret = 0;

        for (ObjectTaskProto.ObjectTaskGetRewardTemp taskGetRewardTemp : reqMsg.getCompletesList()) {
            for (Integer taskId : taskGetRewardTemp.getTaskIdsList()) {
                ret = player.checkObjectTaskComplete(taskGetRewardTemp.getCompleteType(), taskGetRewardTemp.getObjectId(), taskId);
                if (ret > 0) {
                    return ret;
                }
            }
        }

        Property totalReward = new Property();
        for (ObjectTaskProto.ObjectTaskGetRewardTemp taskGetRewardTemp : reqMsg.getCompletesList()) {
            for (Integer taskId : taskGetRewardTemp.getTaskIdsList()) {
                Property reward = player.objectTaskFinish(taskGetRewardTemp.getCompleteType(), taskGetRewardTemp.getObjectId(), taskId);
                if (reward == null) {
                    continue;
                }
                totalReward.addProperty(reward);
            }
        }

        ObjectTaskProto.ObjectTaskGetRewardRespMsg.Builder resp = ObjectTaskProto.ObjectTaskGetRewardRespMsg.newBuilder();
        resp.setRet(0);
        resp.setReward(totalReward.toHelperString());
        player.sendPacket(Protocol.S_OBJECT_TASK_GET_REWARD % 20000, resp);
        return 0;
    }

    public UserObjectTaskData getObjectTaskDataNewIfNull(int objectId, int completeType) {
        if (userObjectTaskDataMap.containsKey(completeType) && userObjectTaskDataMap.get(completeType).containsKey(objectId)) {
            return userObjectTaskDataMap.get(completeType).get(objectId);
        }
        UserObjectTaskData data = null;
        synchronized (userObjectTaskDataMap) {
            if (userObjectTaskDataMap.containsKey(completeType) && userObjectTaskDataMap.get(completeType).containsKey(objectId)) {
                return userObjectTaskDataMap.get(completeType).get(objectId);
            }
            data = new UserObjectTaskData(getUserId(), objectId, completeType);
            if (userObjectTaskDataMap.containsKey(completeType)) {
                userObjectTaskDataMap.get(completeType).put(objectId, data);
            } else {
                Map<Integer, UserObjectTaskData> dataMap = new ConcurrentHashMap<>();
                dataMap.put(objectId, data);
                userObjectTaskDataMap.put(completeType, dataMap);
            }
        }
        return data;
    }
}
